const app = getApp()
import { getMessageDetail } from '../../../api/index'
import { formatTimeTwo } from '../../../utils/util'

Page({
  data: {
    id: '',
    type: '',
    detail: {}
  },
  async getDetail () {
    try {
      let query = {
        id: this.data.id
      }
      if (this.data.type) query.type = this.data.type
      const { ResultSet } = await getMessageDetail({ ...query })
      ResultSet.userData.detail.createTime = formatTimeTwo(ResultSet.userData.detail.createTime, 'Y-D-M h:m:s')
      this.setData({ detail: ResultSet.userData.detail })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.erros, icon: 'none' })
    }
  },
  downloadFile ({ currentTarget: { dataset: { file } } }) {
    wx.showLoading({ title: '下载zhong...', mask: true })
    wx.downloadFile({
      url: file,
      success: function (res) {
        wx.getFileSystemManager().saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            wx.openDocument({
              filePath: res.savedFilePath,
              success: function () {
                wx.hideLoading()
              },
              fail: function (err) {
                if (err.errMsg === 'openDocument:fail filetype not supported') {
                  wx.previewImage({
                    current: res.savedFilePath,
                    urls: [res.savedFilePath]
                  })
                }
                wx.hideLoading()
              }
            })
          },
          fail: function (err) {
            wx.showToast({ title: '保存失败', icon: 'none' })
            wx.hideLoading()
          }
        })
      },
      fail: function (err) {
        wx.showToast({ title: '下载失败', icon: 'none' })
        wx.hideLoading()
      }
    })
  },
  onLoad ({ id, type }) {
    this.setData({ id: parseInt(id), type: parseInt(type) })
    this.getDetail()
  }
})